﻿using System.Text;
using Ooaavee.Data.Model;

namespace Ooaavee.Data.Queries
{
    /// <summary>
    /// This static class exposes static members for a generating SQL query strings.
    /// </summary>
    internal static class SqlStatements
    {
        /// <summary>
        /// The join parameter name.
        /// </summary>
        internal const string JoinParameterName = "@p1";

        /// <summary>
        /// Generates a select-part of the SQL query.
        /// </summary>
        /// <param name="table">Table.</param>
        /// <returns>A part of the SQL query.</returns>
        internal static string BrowseSelect(Table table)
        {
            var s = new StringBuilder();
            foreach (var column in table.Columns)
            {
                if (s.Length > 0)
                {
                    s.Append(", ");
                }
                s.AppendLine(GetColumnName(column));
            }

            s.Insert(0, "SELECT ");

            return s.ToString();
        }

        /// <summary>
        /// Generates a from-part of the SQL query.
        /// </summary>
        /// <param name="table">Table.</param>
        /// <returns>A part of the SQL query.</returns>
        internal static string BrowseFrom(Table table)
        {
            return string.Format("FROM {0}", GetTableName(table));
        }

        /// <summary>
        /// Generates a where-part of the SQL query which will be used when querying data
        /// with a primary key.
        /// </summary>
        /// <param name="primaryKeyColumn">Primary key.</param>
        /// <returns>A part of the SQL query.</returns>
        internal static string BrowseWhere(Column primaryKeyColumn)
        {
            return string.Format("WHERE {0}={1}", GetColumnName(primaryKeyColumn), JoinParameterName);
        }

        private static string GetColumnName(Column column)
        {
            return string.Format("{0}{1}{2}", @"""", column.Name, @"""");
        }

        private static string GetTableName(Table table)
        {
            return string.Format("{0}{1}{2}.{3}{4}{5}.{6}{7}{8}", @"""", table.Catalog, @"""", @"""", table.Schema, @"""", @"""", table.Name, @"""");
        }
    }
}
